package com.shbaiche.bifenba.ui.data;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.data.DataIntegralListAdapter;
import com.shbaiche.bifenba.adapter.data.DataScheduleListAdapter;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.GankResults;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteMatchesMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.data.ShooterMessage;
import com.shbaiche.bifenba.model.data.TeamInfoMessage;
import com.shbaiche.bifenba.model.match.MatchesVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import cn.droidlover.xdroid.base.SimpleRecAdapter;
import cn.droidlover.xdroid.base.XLazyFragment;
import cn.droidlover.xdroidbase.kit.Kits;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerContentLayout;
import cn.droidlover.xrecyclerview.XRecyclerView;
import okhttp3.Call;

/**
 * Created by wanglei on 2016/12/10.
 */

@SuppressLint("ValidFragment")
public class DataScheduleFragment extends XLazyFragment {

    @BindView(R.id.contentLayout)
    XRecyclerContentLayout contentLayout;

    DataScheduleListAdapter adapter;

    CompeteVo mCompeteVo;

    protected static final int PAGE_SIZE = 20;
    protected static final int MAX_PAGE = 50;

    TeamInfoMessage teamInfoMessage;
    private int type = 2;//1:球队详情赛程，2：

    String year = "";

    @SuppressLint("ValidFragment")
    public DataScheduleFragment(){

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event.EventYearChange event) {
        if (event != null && !Kits.Empty.check(event.year)) {
            if(mCompeteVo.equals(event.vo)){
                year = event.year;
                contentLayout.showLoading();
                loadData(1);
            }
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        Log.e("t","initData Schedule");

        if(savedInstanceState!=null && savedInstanceState.containsKey("data")){
            try {
                mCompeteVo = (CompeteVo)savedInstanceState.getSerializable("data");
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(getArguments().containsKey("data")){
            try {
                mCompeteVo = (CompeteVo)getArguments().getSerializable("data");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if(mCompeteVo!=null){
            type = 2;
            if(savedInstanceState!=null && savedInstanceState.containsKey("year")){
                year = savedInstanceState.getString("year");
            }else{
                year = getArguments().getString("year");
            }

            if(TextUtils.isEmpty(year)) {
                if (mCompeteVo != null && mCompeteVo.getMatchesYear() != null && mCompeteVo.getMatchesYear().size() > 0) {
                    year = mCompeteVo.getMatchesYear().get(0);
                } else {
                    int y = new Date(System.currentTimeMillis()).getYear();
                    y += 1900;
                    year = "" + y;
                }
            }
        }else{
            if(savedInstanceState!=null && savedInstanceState.containsKey("message")){
                teamInfoMessage = (TeamInfoMessage) savedInstanceState.getSerializable("message");
            }else{
                teamInfoMessage = (TeamInfoMessage)getArguments().getSerializable("message");
            }
        }

        if(teamInfoMessage!=null){
            type = 1;
        }else{
            type = 2;
        }



        initAdapter();
        if(teamInfoMessage!=null){
            ArrayList<MatchesVo> list = new ArrayList<MatchesVo>();
            MatchesVo vo;
            for (String key : teamInfoMessage.getVoMap().keySet()){
                //list.addAll(result.getVoMap().get(key));
                for (int i=0;i<teamInfoMessage.getVoMap().get(key).size();i++){
                    vo = teamInfoMessage.getVoMap().get(key).get(i);
                    vo.dateShow = key;
                    list.add(vo);
                }
            }
            getAdapter().setData(list);
            if (getAdapter().getItemCount() < 1) {
                contentLayout.showEmpty();
                return;
            }

        }else{
            contentLayout.showLoading();
            loadData(1);
        }
        //
    }

    private void initAdapter() {
        setLayoutManager(contentLayout.getRecyclerView());
        contentLayout.getRecyclerView()
                .setAdapter(getAdapter());

            contentLayout.getRecyclerView()
                    .setOnRefreshAndLoadMoreListener(new XRecyclerView.OnRefreshAndLoadMoreListener() {
                        @Override
                        public void onRefresh() {
                            loadData(1);
                        }

                        @Override
                        public void onLoadMore(int page) {
                            loadData(page);
                        }
                    });

            contentLayout.loadingView(View.inflate(getContext(), R.layout.view_loading, null));
            contentLayout.getRecyclerView().useDefLoadMoreView();

        contentLayout.getEmptyView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentLayout.showLoading();
                loadData(1);
            }
        });


    }

    public void loadData(final int page) {
        if(type == 1){
            contentLayout.getSwipeRefreshLayout().setRefreshing(false);
            contentLayout.showContent();
            return;
        }
        CompeteMatchesMessage message = new CompeteMatchesMessage();
        message.setCompetId(mCompeteVo.getId());
        message.setGameType(mCompeteVo.getGameType());
        message.setPageIndex(page);
        message.setPageSize(PAGE_SIZE);
        message.setYear(year);

        NetApi.dataCompeteMatches(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
                contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                contentLayout.showContent();
                contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                CompeteMatchesMessage result =new Gson().fromJson(response.getMessage(),CompeteMatchesMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getVoList()!=null){
                        Log.e("t","onResponse");
                        if (page > 1) {
                            getAdapter().addData(result.getVoList());
                        } else {
                            getAdapter().setData(result.getVoList());
                        }

                        contentLayout.getRecyclerView().setPage(page, MAX_PAGE);

                        if (getAdapter().getItemCount() < 1) {
                            contentLayout.showEmpty();
                            return;
                        }


                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });

    }



    public SimpleRecAdapter getAdapter() {
        if (adapter == null) {
            adapter = new DataScheduleListAdapter(context);
            adapter.setRecItemClick(new RecyclerItemCallback<MatchesVo, DataScheduleListAdapter.ViewHolder>() {
                @Override
                public void onItemClick(int position, MatchesVo model, int tag, DataScheduleListAdapter.ViewHolder holder) {
                    super.onItemClick(position, model, tag, holder);
                }
            });
        }
        return adapter;
    }


    public void setLayoutManager(XRecyclerView recyclerView) {
        recyclerView.verticalLayoutManager(context);
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_data_schedule;
    }

}
